import 'storage.dart';
import "../../models/goodsdetail_model.dart";

class CartService {
  // 添加购物车记录到本地缓存
  static addCartData(
    GoodsDetailItemModel goodsDetails,
    String selectedAttrStr,
    int buyCount,
  ) async {
    List? cartList = await Storage.getData("cartList");
    if (cartList != null) {
      // cartList已有存在重复商品信息
      bool isDuplicate = cartList.any(
        (item) =>
            item["_id"] == goodsDetails.sId &&
            item["selectedAttr"] == selectedAttrStr,
      );
      if (isDuplicate) {
        // cartList已有重复的数据，只需把数量改变，无需再新增一条数据
        for (int i = 0; i < cartList.length; i++) {
          if (cartList[i]["_id"] == goodsDetails.sId &&
              cartList[i]["selectedAttr"] == selectedAttrStr) {
            // 找到重复的数据，更新数量
            cartList[i]["count"] += buyCount;
            break;
          }
        }
        Storage.setData("cartList", cartList);
      } else {
        // 没有重复数据新增一条数据
        cartList.add({
          "_id": goodsDetails.sId,
          "title": goodsDetails.title,
          "price": goodsDetails.price,
          "selectedAttr": selectedAttrStr,
          "count": buyCount,
          "pic": goodsDetails.pic,
          "checked": true, // 默认选中
        });
        await Storage.setData("cartList", cartList);
      }
    } else {
      // 第一次添加没有购物车记录
      List<Map> tempList = [
        {
          "_id": goodsDetails.sId,
          "title": goodsDetails.title,
          "price": goodsDetails.price,
          "selectedAttr": selectedAttrStr,
          "count": buyCount,
          "pic": goodsDetails.pic,
          "checked": true, // 默认选中
        },
      ];
      await Storage.setData("cartList", tempList);
    }
  }

  // 获取购物车记录
  static Future<List> getCartData() async {
    List? cartList = await Storage.getData("cartList");
    if (cartList != null) {
      return cartList;
    } else {
      return [];
    }
  }

  // 保存更新后的购物车数据
  static Future<void> setCartData(List cartList) async {
    await Storage.setData("cartList", cartList);
  }
  // // 删除某个购物车记录
  // static removeCartData(String keywords) async {
  //   List? cartList = await Storage.getData("cartList");
  //   if (cartList != null) {
  //     cartList.remove(keywords);
  //     await Storage.setData("cartList", cartList);
  //   }
  // }

  // 清空全部购物车搜索记录
  static Future clearCartData() async {
    try {
      await Storage.clearData();
    } catch (e) {
      return "clear error${e.toString()}";
    }
  }
}
